package com.sunny.design.proxy.dynamicproxy.jdkproxy.exam2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 动态代理类
 * 动态根据订单创建年份分库存数据
 *
 * @author Sunny
 * @date 2020/1/1 17:04
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy");

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);

        //执行被代理类的方法
        Object invoke = method.invoke(target, args);

        after();
        return invoke;
    }

    public void before(Object target) {
        try {
            System.out.println("Proxy before method.");
            Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
            int dbRoute = Integer.parseInt(format.format(new Date(time)));
            System.out.println("动态代理类自动分配到【DB_" + dbRoute + "】数据源处理数据。");
            DynamicDataSourceEntry.set(dbRoute);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void after() {
        System.out.println("Proxy after method");
        DynamicDataSourceEntry.restore();
    }
}
